<template>
  <div class="login-index">
    <TransitionGroup name="list" tag="div">
      <div class="content" v-if="type === 'register'">
        <div class="pigce">
          <router-link class="back-home" to="/">
            <el-icon>
              <ArrowLeftBold />
            </el-icon>
          </router-link>
          注册
        </div>
        <el-form ref="registerFormRef" label-width="auto" :model="formData" :rules="rules">
          <el-form-item label="" prop="username">
            <el-input v-model="formData.username" placeholder="用户名" />
          </el-form-item>
          <el-form-item label="" prop="phone">
            <el-input v-model="formData.phone" placeholder="手机号" />
          </el-form-item>
          <el-form-item label="" prop="password">
            <el-input type="password" v-model="formData.password" show-password placeholder="密码" />
          </el-form-item>
          <el-form-item label="" prop="repassword">
            <el-input type="password" v-model="formData.repassword" show-password placeholder="确认密码"
              @keyup.enter="confirm" />
          </el-form-item>
          <!-- <el-form-item label="" prop="ok">
            <el-checkbox v-model="formData.ok" label="我同意用户协议" />
          </el-form-item> -->
          <el-form-item label="" class="confirm-item">
            <el-button type="primary" class="confirm" @click="confirm">注册</el-button>
          </el-form-item>
        </el-form>
        <div class="to-login">
          <!-- <router-link class="back-home" to="/">
            <el-icon>
              <ArrowLeftBold />
            </el-icon>
          </router-link> -->
          <span>已经有一个账号了?</span>
          <a @click="type = 'login'">登录</a>
        </div>
      </div>
      <div class="content" v-else>
        <div class="pigce">
          <router-link class="back-home" to="/">
            <el-icon>
              <ArrowLeftBold />
            </el-icon>
          </router-link>
          登录
        </div>
        <el-form ref="loginFormRef" label-width="auto" :model="formData" :rules="rules">
          <el-form-item label="" prop="phone">
            <el-input v-model="formData.phone" placeholder="手机号" />
          </el-form-item>
          <el-form-item label="" prop="password">
            <el-input type="password" v-model="formData.password" placeholder="密码" show-password
              @keyup.enter="confirm" />
          </el-form-item>
          <el-form-item label="" class="confirm-item">
            <el-button type="primary" class="confirm" @click="confirm">登录</el-button>
          </el-form-item>
        </el-form>
        <div class="to-login">
          <!-- <router-link class="back-home" to="/">
            <el-icon>
              <Back />
            </el-icon>
          </router-link> -->
          <span>还没有账号?</span>
          <a @click="type = 'register'">去注册</a>
        </div>
      </div>
    </TransitionGroup>
  </div>
</template>

<script setup>
import { ArrowLeftBold } from '@element-plus/icons-vue'
import { ref, reactive, watch, nextTick } from "vue";
import { useRoute, useRouter } from "vue-router";
import { ElMessage } from "element-plus";
import { userRegisterService, userLoginService } from "@/api/user";
import useUserStore from "@/stores/user";
import { setLocalStorage } from "@/utils/common";
import constant from "@/constant/index.js";
defineOptions({ name: "LoginIndex" });

const route = useRoute();
const router = useRouter();
// 用户pinia仓库
const userStroe = useUserStore();

const type = ref(route.query.type || "login");
const loginFormRef = ref(null);
const registerFormRef = ref(null);
const formData = reactive({
  username: "",
  phone: "",
  password: "",
  repassword: "",
  ok: true,
});
watch(type, () => {
  Object.assign(formData, {
    username: "",
    phone: "",
    password: "",
    repassword: "",
  });
})
const rules = reactive({
  username: [
    { required: true, message: "请输入用户名", trigger: "blur" },
    { min: 2, max: 15, message: "用户名必须是 2-15位 的字符", trigger: "blur" },
  ],
  phone: [
    { required: true, message: "请输入手机号", trigger: "blur" },
    {
      pattern:
        /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/,
      message: "请输入正确的手机号",
      trigger: "blur",
    },
  ],
  password: [
    { required: true, message: "请输入密码", trigger: "blur" },
    {
      pattern: /^\S{6,15}$/,
      message: "密码必须是6-15位不能有空格",
      trigger: "blur",
    },
  ],
  repassword: [
    { required: true, message: "请输入密码", trigger: "blur" },
    {
      pattern: /^\S{6,15}$/,
      message: "密码必须是6-15位不能有空格",
      trigger: "blur",
    },
    {
      validator: (rule, value, callback) => {
        //判断value和form收集的是否一致
        if (value !== formData.password) {
          callback(new Error("两次输入密码不一致"));
        } else {
          callback();
        }
      },
      trigger: "blur",
    },
  ],
});

const confirm = async () => {
  let oldPhone = formData.phone;
  if (type.value === "login") {
    await loginFormRef.value.validate((valid) => {
      if (valid) {
        userLoginService(formData).then(res => {
          if (res.code === constant.NETWORK.SUCCESS_CODE) {
            ElMessage.success("登录成功");
            // 设置用户信息到pinia
            userStroe.setUser(res.data);
            // 本地存储
            setLocalStorage(constant.USER, res.data);
            // 跳转到上次路由
            router.push(route.query.redirect || "/");
          } else {
            ElMessage.error(res.msg);
          }
        })
      }
    })
  } else {
    await registerFormRef.value.validate((valid) => {
      if (valid) {
        userRegisterService(formData).then((res) => {
          console.log(res);
          // 注册成功
          // 跳转到登录页面
          if (res.code === constant.NETWORK.SUCCESS_CODE) {
            ElMessage.success("注册成功");
            type.value = "login";
            nextTick(() => {
              formData.phone = oldPhone;
            })
          } else {
            ElMessage.error(res.msg);
          }
        });

      }
    });
  }
};
</script>

<style lang="scss" scoped>
.login-index {
  width: 100vw;
  height: 100vh;
  background: #ffffff30;

  &::after {
    content: "";
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-image: url("@/assets/image/login.jpg");
    background-size: cover;
    background-position: center;
    background-repeat: no-repeat;
    filter: blur(10px);
    z-index: -1;
  }

  .content {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    min-width: 320px;
    border-radius: 8px;
    background-color: #fff;
    padding: 20px 16px;
    padding-top: 90px;
    filter: drop-shadow(0 0 10px rgba(0, 0, 0, 0.2));

    .pigce {
      width: 92%;
      height: 80px;
      color: #fff;
      background-color: #3298ee;
      position: absolute;
      top: -15px;
      left: 50%;
      transform: translateX(-50%);
      border-radius: 8px;
      box-shadow: 0 2px 3px 0px #3298ee;
      display: flex;
      justify-content: center;
      align-items: center;
      font-size: 22px;
      font-weight: bold;

      .back-home {
        color: #fff;
        font-size: 20px;
        position: absolute;
        left: 0;
        top: 50%;
        left: 10px;
        transform: translateY(-50%);
      }
    }

    .confirm-item {
      :deep(.el-form-item__content) {
        width: 100%;
        display: flex;
        justify-content: center;
      }

      .confirm {
        width: 90%;
        box-shadow: 0 0 2px 0px var(--el-color-primary);
      }
    }

    .to-login {
      position: relative;
      display: flex;
      justify-content: center;
      align-items: center;

      .back-home {
        color: #409eff;
        font-size: 20px;
        position: absolute;
        left: 0;
        top: 50%;
        left: 10px;
        transform: translateY(-50%);
      }

      span {
        color: #666;
        font-size: 14px;
      }

      a {
        color: var(--el-color-primary);
        margin-left: 4px;
        text-decoration: none;
        cursor: pointer;
      }
    }

    :deep() {
      .el-input__wrapper {
        box-shadow: none !important;
        border-bottom: 1px solid #ccc !important;
        border-radius: 0;
      }
    }
  }
}

.list-enter-active,
.list-leave-active {
  transition: all 0.5s ease-in-out;
}

.list-enter-from,
.list-leave-to {
  opacity: 0;
  transform: translateX(30px) !important;
}
</style>
